package com.huluobo.a2307douyindemo.utils

import BaseCallBack
import FileActionResult
import PermissionResult
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.Toast
import androidx.core.content.FileProvider
import com.huluobo.a2307douyindemo.R
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 *  Created by LC on 2025/9/27.
 */
class FileUtils(private val context: Context, private val activity: Activity, result: PermissionResult) {
    private val permission: PermissionUtils = result.getPermission()
    private lateinit var action: FileActionResult
    private var dialog: BottomSheetDialog<String>? = null
    private lateinit var currentPhotoPath: String

    companion object {
        //文件选择
        private const val FILE_SELECT_CODE = 10109

        //多文件选择
        private const val FILE_MULTIPLE_SELECT_CODE = 10108

        //拍照
        private const val TAKE_PICTURE = 10110

        //选择视频
        private const val FILE_SELECT_VIDEO = 10119

        //拍视频
        private const val TAKE_VIDEO = 10120
    }

    fun setAction(action: FileActionResult) {
        this.action = action
    }

    //打开拍照的底部弹窗
    fun openImage(actions: Array<String>?) {
        if (actions == null || actions.size != 1) {
            if (dialog == null) {
                val pictureLayout =
                    LayoutInflater.from(context).inflate(R.layout.layout_picture_select, null) as LinearLayout
                dialog = BottomSheetDialog(context, pictureLayout)
                pictureLayout.findViewById<View>(R.id.camera).setOnClickListener {
                    dialog!!.dismiss()
                    //拍照
                    takePhoto()
                }
                pictureLayout.findViewById<View>(R.id.album).setOnClickListener {
                    dialog!!.dismiss()
                    //打开相册
                    selectImage(false)
                }
            }
            dialog!!.show()
        } else {
            if (actions[0] == "album") {
                //打开相册
                selectImage(false)
            } else {
                //拍照
                takePhoto()
            }
        }
    }

    //选择图片的方法,跳转到系统相册
    private fun selectImage(multiple: Boolean) {
        permission.setCallBack(object : BaseCallBack<Int> {
            override fun success(data: Int) {
                if (data == PermissionUtils.AUTHORIZED) {
                    selectImage(multiple)
                }
            }
        })

        val image = permission.requestPermission(PermissionUtils.Type.Image)
        if (image == PermissionUtils.UNAUTHORIZED || image == PermissionUtils.REJECTED) {
            return
        }

        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        if (multiple) {
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
        }
        activity.startActivityForResult(
            Intent.createChooser(intent, "选择图片"),
            if (multiple) FILE_MULTIPLE_SELECT_CODE else FILE_SELECT_CODE
        )
    }

    //拍摄图片
    private fun takePhoto() {
        permission.setCallBack(object : BaseCallBack<Int> {
            override fun success(data: Int) {
                if (data == PermissionUtils.AUTHORIZED) {
                    takePhoto()
                }
            }
        })

        //判断相机和读取图片的权限,如果未授权,不向下执行
        val camera = permission.requestPermission(PermissionUtils.Type.Camera)
        if (camera == PermissionUtils.UNAUTHORIZED || camera == PermissionUtils.REJECTED) {
            return
        }
        val image = permission.requestPermission(PermissionUtils.Type.Image)
        if (image == PermissionUtils.UNAUTHORIZED || image == PermissionUtils.REJECTED) {
            return
        }
        val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        try {
            val phoneFile = createImageFile()
            val phoneURI = FileProvider.getUriForFile(
                context,
                "${context.packageName}.fileprovider", // 必须与 manifest 中的 authority 匹配
                phoneFile!!
            )
            //通过intent生成文件
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, phoneURI)
            //使用获取结果的打开activity方式,可以获取到拍摄之后的图片路径
            activity.startActivityForResult(takePictureIntent, TAKE_PICTURE)
            // 检查是否有应用可以处理这个 intent
            if (takePictureIntent.resolveActivity(context.packageManager) != null) {
                activity.startActivityForResult(takePictureIntent, 102)
            } else {
                Toast.makeText(context, "未找到相机应用", Toast.LENGTH_SHORT).show()
            }
        } catch (e: IOException) {
            Log.e("TagA", "拍照文件生成错误:$e")
        }
    }

    //创建图片文件
    private fun createImageFile(): File? {
        //创建一个唯一的文件名
        val timesTamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val imageFileName = "huluobo" + timesTamp + "_"

        //获取应用的外部存储目录
        val storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)

        //创建文件 文件名,文件后缀,文件路径
        val imageFile = File.createTempFile(imageFileName, ".png", storageDir)
        // 如果父目录不存在则创建
        imageFile.parentFile?.mkdirs()
        //保存文件路径
        currentPhotoPath = imageFile.absolutePath
        return imageFile
    }

    //打开拍摄视频的底部弹窗
    fun openVideo(actions: Array<String>?) {
        if (dialog == null || actions?.size != 1) {
            if (dialog == null) {
                val pictureLayout =
                    LayoutInflater.from(context).inflate(R.layout.layout_picture_select, null) as LinearLayout
                dialog = BottomSheetDialog(context, pictureLayout)
                pictureLayout.findViewById<View>(R.id.camera).setOnClickListener {
                    dialog!!.dismiss()
                    //选择视频
                }
                pictureLayout.findViewById<View>(R.id.album).setOnClickListener {
                    dialog!!.dismiss()
                    //选择视频
                }
            }
        }
    }
}